<template>
  <div>
    <!-- 头部面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home ' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示框 -->
      <el-alert title="添加商品信息" center :closable="false" type="info" show-icon>
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeindex - 1" align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form ref="addform" :rules="AddRules" :model="addForm" label-position="top" label-width="80px">
        <el-tabs v-model="activeindex" @tab-click="TabClicked" :before-leave="beforeTabLeave" :tab-position="tabPosition"
          style="height: 100%;">
          <el-tab-pane label="基本信息" name="1">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品的价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-cascader v-model="addForm.goods_cat" :options="getCategoriesList" expandTrigger="hover" :props="Cascader"
              @change="handleChange()"></el-cascader>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="2">
            <el-form-item :label="itme.attr_name" v-for="itme in manyTableData" :key="itme.attr_id">
              <el-checkbox-group v-model="itme.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in itme.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="3">
            <el-form-item :label="itme.attr_name" v-for="itme in onlyTableData" :key="itme.attr_id">
              <el-input v-model="itme.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="4">
            <!-- action 表示图片要上传的后台 API 地址 -->
            <el-upload class="upload-demo" :action="uploadURL" :headers="headersObj" :on-success="handleSuccess"
              :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="6">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add" class="btnAdd">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="ImgeVisible" width="50%">
      <span slot="footer" class="dialog-footer">
        <el-image :src="tpm_path" class="img"></el-image>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 进度条的进度
      activeindex: '1',
      // 添加标的数据
      addForm: {
        // 商品名称
        goods_name: '',
        // 价格
        goods_price: 0,
        // 数量
        goods_number: 0,
        // 重量
        goods_weight: 0,
        // 介绍
        goods_introduce: '',
        // 绑定级联选择的数据
        goods_cat: [],
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: []
      },
      // 卡片所选择位置
      tabPosition: '',
      // 定义tabs方向
      tabPosition: 'left',
      // 定义表单验证规则
      AddRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 接收商品分类的数据
      getCategoriesList: [],
      // 级联选择器的配置
      Cascader: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 接收动态参数
      manyTableData: [],
      // 接收静态参数
      onlyTableData: [],
      // 定义文件上传
      fileList: [],
      // 上传地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 设置图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览图片路径
      tpm_path: '',
      // 控制预览窗口是否显示
      ImgeVisible: false
    }
  },
  created() {
    this.getCategories()
  },
  methods: {
    // 获取所有商品分类
    async getCategories() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) return
      this.getCategoriesList = res.data
    },
    // 监听
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '1' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请选择商品分类')
        return false
      }
    },
    // 监听级联选择内容
    handleChange() {
      // 只能选中三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.value = []
      }
    },
    // 点击tab 的时候触发
    async TabClicked() {
      const { data: res } = await this.$http.get(`categories/${this.cahrid}/attributes`, {
        params: { sel: this.Clicked }
      })
      if (this.Clicked === 'many') {
        res.data.forEach(itme => {
          itme.attr_vals = itme.attr_vals.length === 0 ? [] : itme.attr_vals.split(' ')
          if (res.meta.status !== 200) return this.$message.error('获取动态参数失败')
          this.manyTableData = res.data
        })
      } else if (this.Clicked === 'only') {
        if (res.meta.status !== 200) return this.$message.error('获取静态参数失败')
        this.Clicked === 'only' ? this.onlyTableData = res.data : ''
      }
    },

    // 点击预览图片
    handlePreview(file) {
      // 显示图片预览弹窗
      this.ImgeVisible = true
      console.log(file.response)
      // 获取要预览的图片地址 并 赋值预览路径
      this.tpm_path = file.response.data.url
    },
    // 删除上传文件
    handleRemove(file, fileList) {
      // 1 获取将要删除的图片路径 找个图片的路径并删除返回一个新的 数组
      const pics_path = this.addForm.pics.filter((itme) => itme.pic !== file.response.data.tmp_path)
      // 建获取到的数组重新赋值给 addFrom.pics
      this.addForm.pics = pics_path
    },
    // 监听文件是否上传成功
    handleSuccess(success, file, fileList) {
      // 1 . 拼接得到一个图片信息对象
      const picinfo = { pic: success.data.tmp_path }
      // 2. 将图片信息对象 push 到 pics 数组中
      this.addForm.pics.push(picinfo)
      console.log(this.addForm)
    },
    // 添加商品按钮
    add() {
      this.$refs.addform.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
        // 执行添加的业务逻辑
        // lodash   cloneDeep(obj)
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs

        // 发起请求添加商品
        // 商品的名称，必须是唯一的
        const { data: res } = await this.$http.post('goods', form)

        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败！')
        }
        this.$message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    cahrid() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
    Clicked() {
      if (this.activeindex === '2') {
        return 'many'
      } else if (this.activeindex === '3') {
        return 'only'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-card__body {
  width: 100%;
}

.el-checkbox {
  margin: 0 10px !important;
}

.img {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}
</style>
